<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="author" content="yrh">
    <title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<!--login-->
<form action="/loginxxx" method="post">
    <input type="text" name="username" id="username"><br>
    <input type="text" name="password" id="password"><br>
    <button id="loginbtn">登录</button>
</form>

<script>
    document.getElementById("loginbtn").addEventListener("click", function (ev) {
        ev.preventDefault()
        console.log("=============")
        let xhr = new XMLHttpRequest();
        xhr.open("post", "http://localhost:8080/api/login");
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                //1.cookies 2.sessionStorge 3localstorge 4数据库
                if (xhr.status === 200) {
                    console.log("返回的响应" + xhr.responseText);
                    let parse = JSON.parse(xhr.responseText);
                    if (parse.resCode === 1) {
                        let token = parse.data;
                        localStorage.setItem("token", token)
                        //登录成功，跳转到userdetail.html
                        location.href = "http://" + location.host + "/userdetail.html"
                    } else {

                    }
                } else {
                    console.log("error" + xhr.status, xhr.responseText);
                }
            }
        }
        //json
        let username = document.getElementById("username").value;
        let psw = document.getElementById("password").value;
        let data = JSON.stringify({
            name: username,
            password: psw
        })
        xhr.send(data)
    })
</script>

</body>
</html>